﻿namespace BM.Tools.WebControls.MForm
{
    using System.Diagnostics.CodeAnalysis;
    using System.Xml;
    using System.Xml.Serialization;

    /// <summary>
    /// This class can be used to quickly convert xml node into an object of a specified type.
    /// </summary>    
    public static class XmlToObjectConverter
    {
        /// <summary>
        /// Converts the xml node into an object
        /// </summary>
        /// <param name="node">
        /// The node from which the object is created.
        /// </param>
        /// <typeparam name="TObject">
        /// the type of the object.
        /// </typeparam>
        /// <returns>
        /// the object of the generic type.
        /// </returns>
        [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", MessageId = "System.Xml.XmlNode", Justification = "Specific functionality provided by the concrete type is required")]
        [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "This method ensures type safety and the use of generics is required.")]
        public static TObject ToObject<TObject>(XmlNode node) where TObject : class 
        {
            var serializer = new XmlSerializer(typeof(TObject));
            using (var nodeReader = new XmlNodeReader(node))
            {
                return serializer.Deserialize(nodeReader) as TObject;
            }
        }
    }
}
